package com.dxyxx.framework;

import java.util.List;

import org.apache.http.Header;
import org.codehaus.jackson.type.JavaType;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import br.com.pierry.simpletoast.SimpleToast;

import com.dxyxx.R;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.Group;
import com.dxyxx.pojo.GroupInstance;
import com.dxyxx.pojo.Order;
import com.dxyxx.pojo.OrderDetail;
import com.dxyxx.pojo.ResponseResult;
import com.dxyxx.pojo.User;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class OrderDoneActivity extends BaseActivity {
	private TextView orderMoney;
	private TextView orderDeliveryType;
	private TextView et_dtime;
	private TextView groupInstanceIdView;
	private TextView uuidViews;
	private LinearLayout l0;
	//	private TextView orderId;
	private ImageView et_payType;
	private ViewGroup rootViewGroup;

	private ProgressDialog progressDialog;
	private ListView teamersListView;
	private Button bufferCode;
	// 几人团
	private int groupAmount;
	private int userAmount;
	private Bundle bundle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_orderdone);
		initViews();
		rootViewGroup = (ViewGroup) findViewById(R.id.content);
		// 根据id 拿到信息。
		RequestParams rp = new RequestParams();
		bundle = this.getIntent().getExtras();
		rp.add("id", bundle.getString("id"));
		String url = null;
		char c = bundle.getString("uuid").charAt(0);
		switch (c) {
		case 'g':// 开团吧
			url = "gorder/findById";
			break;
		case 'o':
			url = "order/findById";
			break;
		case 't':
			url = "order/findTicketById";
			break;
		default:
			url = "order/findById";
			break;
		}
		// 启动 等待框架
		progressDialog = ProgressDialog.show(this, null, null);
		progressDialog.setContentView(R.layout.dialog_circle);
		HttpUtil.get(url, rp, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				AgainPlayer.makeCall(OrderDoneActivity.this, "网络好像出错了");
			}

			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				try {
					JavaType type = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, Order.class);
					ResponseResult<Order> result = getObjectMapper().readValue(arg2, type);
					if (result.getCode() == 1) {
						Order order = result.getObject();
						uuidViews.setText(order.getUuid());
						orderMoney.setText("￥" + df.format(order.getMoney()));
						orderDeliveryType.setText("自提");
						switch (order.getBufferInterval()) {
						case 0:
							et_dtime.setText("当天");
							break;
						case 1:
							et_dtime.setText("下单后第二天");
							break;
						case 2:
							et_dtime.setText("下单后第三天");
							break;

						default:
							et_dtime.setText("当天");
							break;
						}
						//					orderId.setText(order.getUuid());
						if (order.getPayType().equals("alipay")) {
							et_payType.setImageResource(R.drawable.alipay_icon);
						} else {
							et_payType.setImageResource(R.drawable.wechat);
						}
						//Order 
						if (order.getOrderDetails() != null) {
							for (OrderDetail od : order.getOrderDetails()) {
								View view = (ViewGroup) getLayoutInflater().inflate(R.layout.item_orderconfirm, null, false);
								((TextView) view.findViewById(R.id.price)).setText(od.getPrice() + "");
								((TextView) view.findViewById(R.id.amount)).setText("*" + od.getAmount() + "=  ");
								((TextView) view.findViewById(R.id.all)).setText(df.format(od.getPrice() * od.getAmount()));
								((TextView) view.findViewById(R.id.description)).setText(od.getProduct().getDescription());
								((TextView) view.findViewById(R.id.specification)).setText(od.getProduct().getSpecification());
								imageLoader.displayImage(baseImageURL + od.getProduct().getThumbId() + "?p=0", (ImageView) view.findViewById(R.id.thumb), squareOptions, animateFirstListener);
								rootViewGroup.addView(view);
							}
						}
						// GroupOrder
						Group group = order.getGroup();
						if (group != null) {//属于团购
							groupInstanceIdView.setText(order.getGroupInstance().getId() + "");
							View view = (ViewGroup) getLayoutInflater().inflate(R.layout.item_orderconfirm, null, false);
							((TextView) view.findViewById(R.id.price)).setText(group.getPersonPrice() + "");
							((TextView) view.findViewById(R.id.amount)).setText("*1" + "=  ");
							((TextView) view.findViewById(R.id.all)).setText(group.getPersonPrice() + "");
							((TextView) view.findViewById(R.id.description)).setText(group.getProduct().getDescription());
							((TextView) view.findViewById(R.id.specification)).setText(group.getProduct().getSpecification());
							imageLoader.displayImage(baseImageURL + group.getProduct().getThumbId() + "?p=0", (ImageView) view.findViewById(R.id.thumb), squareOptions, animateFirstListener);
							rootViewGroup.addView(view);
							GroupInstance gi = order.getGroupInstance();
							/// 显示团员 团长的情况。
							View teamerView = (ViewGroup) getLayoutInflater().inflate(R.layout.view_teamers, null, false);
							// 表明几人团
							groupAmount = group.getPersonAmount();
							((TextView) teamerView.findViewById(R.id.groupDesc)).setText("团长【" + group.getPersonAmount() + "人团】");
							ImageView captainImage = (ImageView) teamerView.findViewById(R.id.captain);
							TextView captainName = (TextView) teamerView.findViewById(R.id.captainName);
							if (gi.getCaptain().getImage() != null) {
								imageLoader.displayImage(baseImageURL + gi.getCaptain().getImage() + "?p=0", captainImage, squareOptions, animateFirstListener);
							}
							captainName.setText(gi.getCaptain().getUsername());

							//							teamersListView = (ListView) teamerView.findViewById(R.id.teamer);
							rootViewGroup.addView(teamerView);
							//得到group instance id 。。访问url ，刷新团员信息。
							HttpUtil.get("groupinstance/get?groupinstanceId=" + gi.getId(), new AsyncHttpResponseHandler() {

								@Override
								public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
									try {

										JavaType javaType1 = getObjectMapper().getTypeFactory().constructCollectionType(List.class, User.class);

										JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, javaType1);

										ResponseResult<List<User>> result = getObjectMapper().readValue(arg2, javaType);
										if (result.getCode() == 1) {
											for (User u : result.getObject()) {
												View itemView = (ViewGroup) getLayoutInflater().inflate(R.layout.item_teamers, null, false);

												if (u.getImage() != null) {
													imageLoader.displayImage(baseImageURL + u.getImage() + "?p=0", (ImageView) itemView.findViewById(R.id.teamerImage), squareOptions, animateFirstListener);
												}
												((TextView) itemView.findViewById(R.id.teamerName)).setText(u.getUsername());
												if (u.getCreateTime() != null) {
													((TextView) itemView.findViewById(R.id.date)).setText("下单时间：" + sdf.format(u.getCreateTime()));
												}
												rootViewGroup.addView(itemView);
											}
											userAmount = result.getObject().size();
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								}

								@Override
								public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
									SimpleToast.info(OrderDoneActivity.this, "获取团员列表失败");

								}
							});
							// 处理提货券， 查看团员人数 是否齐了。
							bufferCode.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									if (userAmount >= groupAmount) {
										Intent intent = new Intent(OrderDoneActivity.this, CommonBarcodeActivity.class);
										intent.putExtra("code", bundle.getString("uuid"));
										startActivity(intent);
									} else {
										SimpleToast.error(OrderDoneActivity.this, "团员人数没有达到要求");
									}

								}
							});
						} else { // 隐藏 团号
							l0.setVisibility(View.GONE);
							// 非团购。直接显示  提货券
							bufferCode.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									Intent intent = new Intent(OrderDoneActivity.this, CommonBarcodeActivity.class);
									intent.putExtra("code", bundle.getString("uuid"));
									startActivity(intent);

								}
							});
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			};

			@Override
			public void onFinish() {
				progressDialog.dismiss();
				super.onFinish();
			}
		});

	}

	public void initViews() {
		((ImageView) findViewById(R.id.backImageButton)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		((ImageView) findViewById(R.id.nextImageButton)).setVisibility(View.INVISIBLE);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("已付款");
		title.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
		//

		orderMoney = (TextView) findViewById(R.id.orderMoney);
		orderDeliveryType = (TextView) findViewById(R.id.orderDeliveryType);
		et_dtime = (TextView) findViewById(R.id.et_dtime);
		//		orderId = (TextView) findViewById(R.id.orderId);
		et_payType = (ImageView) findViewById(R.id.payIcon);
		groupInstanceIdView = (TextView) findViewById(R.id.groupInstanceId);
		uuidViews = (TextView) findViewById(R.id.uuidViews);
		bufferCode = (Button) findViewById(R.id.bufferCode);
		l0 = (LinearLayout) findViewById(R.id.l0);

	}
}
